package com.example.work.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.work.entity.*;
import com.example.work.entity.vo.*;
import com.example.work.service.*;
import com.example.work.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/score")
public class AreaScoreController {

    @Autowired
    private ITbCheckAreaScoreService areaScoreService;

    @Autowired
    private ITbHospCheckCategoryService hospCheckCategoryService;

    @Autowired
    private ITbCheckItemScoreService itemScoreService;

    @Autowired
    private ITbCheckDeficiencyService deficiencyService;


    @Autowired
    private ITbCheckBatchService tbCheckBatchService;

    @Autowired
    private ITbHospCheckCategoryService tbHospCheckCategoryService;


    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IAreaService areaService;

    @Autowired
    private IAreaItemService areaItemService;

    @Autowired
    private IDbHospService dbHospService;

    /**
     * 按照区域打分，并进行问题留痕
     **/
    @PostMapping("/area")
    @Transactional(rollbackFor = Exception.class)
    public R postAreaScore(@RequestBody PutAreaScoreVo areaScore) {

        if (areaScore == null)
            return R.error("打分内容为空");
        // System.out.println(areaScore.toString());
        try {
            //判断是否已经存在该区域，若存在则更新，若不存在则新增
            TbCheckAreaScore tbCheckAreaScore = areaScore.getAreaScore();
            TbCheckAreaScore tbSqlCheckAreaScore = areaScoreService.lambdaQuery().eq(TbCheckAreaScore::getBatchId,tbCheckAreaScore.getBatchId())
                    .eq(TbCheckAreaScore::getCategoryId,tbCheckAreaScore.getCategoryId())
                    .eq(TbCheckAreaScore::getAreaId,tbCheckAreaScore.getAreaId()).one();
            if(tbSqlCheckAreaScore!=null){
                tbCheckAreaScore.setId(tbSqlCheckAreaScore.getId());
                tbSqlCheckAreaScore.setUpdateTime(new Date());
            }
            if (!areaScoreService.save(tbCheckAreaScore))
                throw new Exception();
            // 观察是否有id
            // 如果有id，则设置item的id
            // System.out.println("插入后获取id： " +  tbCheckAreaScore.getId());

            // 插入所有的item score项目
            for (PutItemScoreVo itemScore : areaScore.getItems()) {
                TbCheckItemScore tbCheckItemScore = itemScore.getItemScore();
                tbCheckItemScore.setAreaScoreId(tbCheckAreaScore.getId());

                //如果存在则更新
                TbCheckItemScore tbSqlCheckItemScore = itemScoreService.lambdaQuery().eq(TbCheckItemScore::getBatchId,tbCheckItemScore.getBatchId())
                        .eq(TbCheckItemScore::getCategoryId,tbCheckItemScore.getCategoryId())
                        .eq(TbCheckItemScore::getAreaId,tbCheckItemScore.getAreaId())
                        .eq(TbCheckItemScore::getItemId,tbCheckItemScore.getItemId()).one();
                if(tbSqlCheckItemScore!=null){
                    tbCheckItemScore.setId(tbSqlCheckItemScore.getId());
                    tbSqlCheckItemScore.setUpdateTime(new Date());
                }

                // System.out.println(tbCheckItemScore.toString());
                if (!itemScoreService.save(tbCheckItemScore))
                    throw new Exception();

                // System.out.println(itemScore);
                // System.out.println(itemScore.getRemark());
                //问题留痕
                if (null != itemScore.getRemark()) {
                    TbCheckDeficiency
                            deficiency = deficiencyService.lambdaQuery()
                            .eq(TbCheckDeficiency::getObjectScoreId, tbCheckItemScore.getId())
                            .one();
                    if (deficiency == null)
                        deficiency = new TbCheckDeficiency();
                    deficiency.setObjectScoreId(tbCheckItemScore.getId());
                    deficiency.setItemId(tbCheckItemScore.getItemId());
                    deficiency.setAreaId(tbCheckItemScore.getAreaId());
                    deficiency.setCategoryId(tbCheckItemScore.getCategoryId());
                    deficiency.setBatchId(tbCheckItemScore.getBatchId());
                    deficiency.setHospId(tbCheckItemScore.getHospId());
                    deficiency.setCreateTime(LocalDateTime.now());
                    deficiency.setCreateBy(tbCheckItemScore.getCreateBy());
                    deficiency.setRemark(itemScore.getRemark());
                    deficiency.setDeleteFlag(false);

                    deficiencyService.AreaItemDeficiency(deficiency);
                }
            }
            return R.ok();

        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }


    /**
     * 根据hospCheckCategory获取其下的所有的区域及其项目，将其装饰后返回
     **/
    @GetMapping("/category/{id}")
    public R getCateGoryItemsVo(@PathVariable String id) {


        // 获取hospCheckCategory
        TbHospCheckCategory hospCheckCategory = hospCheckCategoryService.getById(id);

        // 获取category和hosp
        DbCheckCategory category = categoryService.getById(hospCheckCategory.getCategoryId());
        Dbhosp hosp = dbHospService.getById(hospCheckCategory.getHospId());

        // 获取areas
        List<PutAreaScoreVo> areaScoreVoList = areaScoreService.getPutAreaScoreVo(category.getId(), hospCheckCategory.getBatchId(), hospCheckCategory.getHospId());

        PutCategoryScoreVo categoryScoreVo = new PutCategoryScoreVo();

        categoryScoreVo.setHospCheckCategory(hospCheckCategory);
        categoryScoreVo.setCategoryName(category.getName());
        categoryScoreVo.setHospName(hosp.getHospName());
        categoryScoreVo.setAreas(areaScoreVoList);

        Map<String, Object> map = new HashMap<>();
        map.put("data", categoryScoreVo);

        return R.ok(map);
    }


    /**
     * 获取分数批次下的区域打分明细
     */
    @GetMapping("/getBatchScoreInfo")
    public R getBatchAreaScores(@RequestParam String batchId) {

        if (batchId == null || batchId.trim().isEmpty()) {
            return R.error("批次ID不能为空");
        }

        try {
            // 调用服务获取批次信息和打分明细
            BatchCategoryScoreResponse response = getBatchCategoryScores(batchId);
            return R.ok().put("data", response);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取批次区域打分明细失败: " + e.getMessage());
        }
        //
    }


    private BatchCategoryScoreResponse getBatchCategoryScores(String batchId) {

        BatchCategoryScoreResponse response = new BatchCategoryScoreResponse();

        // 1. 获取批次信息（减少不必要的属性单独设置）
        TbCheckBatch batch = tbCheckBatchService.getById(batchId);
        if (batch != null) {
            response.setBatchName(batch.getName());
            response.setBatchStatus(batch.getStatus());
            response.setSummarizeProblem(batch.getSummarizeProblem());
            response.setSummarizeHighlight(batch.getSummarizeHighlight());
            response.setSummarizeNeedImprove(batch.getSummarizeNeedImprove());
        }

        // 2. 获取考核分类及相关信息
        List<TbHospCheckCategory> categories = tbHospCheckCategoryService.lambdaQuery()
                .eq(TbHospCheckCategory::getBatchId, batchId).list();
        if (categories.isEmpty()) {
            response.setCategories(new ArrayList<>());
            return response;
        }

        // 提前批量查询所需的分类名称、区域名称、项目名称，避免多次查询
        Map<String, String> categoryNameMap = categoryService.lambdaQuery()
                .select(DbCheckCategory::getId, DbCheckCategory::getName)
                .list().stream().collect(Collectors.toMap(DbCheckCategory::getId, DbCheckCategory::getName));

        Map<String, String> areaNameMap = areaService.lambdaQuery()
                .select(TbCheckArea::getId, TbCheckArea::getName)
                .list().stream().collect(Collectors.toMap(TbCheckArea::getId, TbCheckArea::getName));

        Map<String, String> itemNameMap = areaItemService.lambdaQuery()
                .select(TbCheckAreaItem::getId, TbCheckAreaItem::getName)
                .list().stream().collect(Collectors.toMap(TbCheckAreaItem::getId, TbCheckAreaItem::getName));

        // 3. 处理分类信息
        List<BatchCategoryScoreResponse.CategoryScore> categoryScores = new ArrayList<>();
        for (TbHospCheckCategory category : categories) {
            BatchCategoryScoreResponse.CategoryScore categoryScore = new BatchCategoryScoreResponse.CategoryScore();
            categoryScore.setCategoryName(categoryNameMap.get(category.getCategoryId()));

            // 获取区域分数
            List<TbCheckAreaScore> areaScores = areaScoreService.getCategoryArea(category.getCategoryId(), batchId, category.getHospId());
            List<BatchCategoryScoreResponse.CategoryScore.AreaScore> areaScoreList = new ArrayList<>();

            BigDecimal areaScoreSunm = BigDecimal.ZERO;
            for (TbCheckAreaScore areaScore : areaScores) {
                BatchCategoryScoreResponse.CategoryScore.AreaScore area = new BatchCategoryScoreResponse.CategoryScore.AreaScore();
                area.setAreaName(areaNameMap.get(areaScore.getAreaId()));
                area.setAreaScore(areaScore.getScore());
                areaScoreSunm=areaScoreSunm.add(areaScore.getScore());

                // 获取项目分数
                List<TbCheckItemScore> itemScores = itemScoreService.getAreaItems(areaScore.getAreaId(),batch.getId());
                List<BatchCategoryScoreResponse.CategoryScore.AreaScore.ItemScore> itemScoreList = new ArrayList<>();

                for (TbCheckItemScore itemScore : itemScores) {
                    TbCheckDeficiency itemdeficiency= new TbCheckDeficiency();
                    QueryWrapper<TbCheckDeficiency> queryWrapper = new QueryWrapper<>();
                    System.out.println(itemScore.getId());
                    queryWrapper.eq("object_score_id", itemScore.getId()); // 假设数据库字段为 object_id
                    itemdeficiency=deficiencyService.getOne(queryWrapper);
                    System.out.println(itemdeficiency);
                    BatchCategoryScoreResponse.CategoryScore.AreaScore.ItemScore item = new BatchCategoryScoreResponse.CategoryScore.AreaScore.ItemScore();
                    item.setItemName(itemNameMap.get(itemScore.getItemId()));
                    item.setItemScore(itemScore.getScore());
                    if (itemdeficiency == null ) { item.setRemark("null");}
                    else {item.setRemark(itemdeficiency.getRemark());}
                    itemScoreList.add(item);
                }
                area.setItems(itemScoreList);
                areaScoreList.add(area);
            }
            categoryScore.setAreas(areaScoreList);
            categoryScore.setCategoryScore(areaScoreSunm);
            categoryScores.add(categoryScore);
        }
        response.setCategories(categoryScores);
        return response;

    }
}
